package jerry;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import sun.net.ftp.FtpClient;

/**
 * 
 * This class will upload the content to the
 * ftp site where the htmls will be hosted.
 * 
 * 
 * @author (h0t@_G0|i
 *
 */
public class FtpUploader {

	private static byte[] b = new byte[9000];
	/**
	 * Method to communicate with the FTP site.
	 * 
	 * @param htmlsDir
	 * @param ftpHostName
	 * @throws IOException 
	 */
	public static void uploadToFtpSite(File htmlsDir, String ftpHostName) throws IOException {
		if(ftpHostName == null) {
			return;
		}
		FtpClient client = new FtpClient(ftpHostName, Integer.parseInt(ListenTCP.getProperty("ftp.port")));
		String username = ListenTCP.getProperty("ftp.username");
		String password = ListenTCP.getProperty("ftp.password");
		if(username != null)
			client.login(username, password);
		System.out.println(client.welcomeMsg);
		if(htmlsDir.isDirectory()) {
			for(File inner : htmlsDir.listFiles()) {
				if(inner.isDirectory()) {
					putDirectory(inner, client);
				} else {
					putFile(inner, client);
				}
			}
		}
	}

	/**
	 * Adds the file to FTP server.
	 * 
	 * @param inner
	 * @param client
	 * @throws IOException
	 */
	private static void putFile(File inner, FtpClient client) throws IOException {
		OutputStream stream = client.put(inner.getName());
		InputStream iStream = new FileInputStream(inner);
		int available = iStream.read(b);
		while(available >= 0) {
			stream.write(b, 0, available);
			stream.flush();
			available = iStream.read(b);
		}
		stream.close();
		iStream.close();
	}

	/**
	 * Recursively adds directories and adds all 
	 * files in that directory to the server.
	 * 
	 * @param inner
	 * @param client
	 * @throws IOException
	 */
	private static void putDirectory(File inner, FtpClient client) throws IOException {
		try{
			client.cd(inner.getName());
		} catch (Exception e) {
			client.sendServer("md "+inner.getName());
			client.cd(inner.getName());
		}
		for(File f : inner.listFiles()){
			if(f.isDirectory()) {
				putDirectory(f, client);
			} else {
				putFile(f,client);
			}
		}
		client.cdUp();
	}
} 